#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct Node
{
    int level;
    TreeNode *ptr;
    Node(int level, TreeNode *ptr = NULL) : level(level), ptr(ptr){};
};
class Solution
{
public:
    queue<Node> que;
    vector<vector<int>> ans;
    vector<int> slice;
    vector<vector<int>> levelOrderBottom(TreeNode *root)
    {
        Node nd = *new Node(0, root);
        int nowlevel = 0;
        que.push(nd);
        while (que.empty() == false)
        {
            nd = que.front();
            que.pop();
            if (nd.ptr == NULL)
                continue;
            if (nd.level > nowlevel)
            {
                ans.push_back(slice);
                slice.clear();
                nowlevel++;
            }
            slice.push_back(nd.ptr->val);
            que.push(Node(nd.level + 1, nd.ptr->left));
            que.push(Node(nd.level + 1, nd.ptr->right));
        }
        if (slice.empty() == false)
            ans.push_back(slice);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};